package com.logic.landseaserver.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.security.SecurityUtils;
import com.logic.common.util.JsonMapper;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.domain.ConfigurationQiyuesuo;
import com.logic.landseaserver.domain.DdingProjectConfig;
import com.logic.landseaserver.domain.WebankParam;
import com.logic.landseaserver.models.payment.service.ShiJiPaymentService;
import com.logic.landseaserver.persistence.read.WebankParamReadMapper;
import com.logic.landseaserver.persistence.write.WebankParamWriteMapper;
import com.logic.landseaserver.service.IConfigurationQiyuesuoService;
import com.logic.landseaserver.service.IDdLockService;
import com.logic.landseaserver.service.IParamConfigService;
import com.logic.landseaserver.service.IProjectService;
import com.logic.landseaserver.ws.dto.ParamConfigDTO;
import com.logic.landseaserver.ws.dto.ProjectDetailDTO;

/**
*@author Tony
*/

@Service
public class ParamConfigServiceImpl implements IParamConfigService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
	@Autowired
	private WebankParamReadMapper webankParamReadMapper;

	@Autowired
	private WebankParamWriteMapper webankParamWriteMapper;

	@Autowired
	private IConfigurationQiyuesuoService configurationQiyuesuoService;

	@Autowired
    private IDdLockService ddLockService;

	@Autowired
	private IProjectService projectService;

    @Autowired
    private ShiJiPaymentService shiJiPaymentService;
	@Override
	public String saveOrUpdateParam(ParamConfigDTO configDto) {
		StringBuffer errorMSG = new StringBuffer();
		HashMap<String, Object> map = new HashMap<String, Object>();
		//微众收银台
		if(validateParams(configDto)){
			try{
				WebankParam webankParam = new WebankParam();
				if(configDto.getPrjId()!=null)
				webankParam.setPrjId(configDto.getPrjId());
				if(configDto.getWwMerchantId()!=null)
				webankParam.setwMerchantId(configDto.getWwMerchantId());
				if(configDto.getWwMerchantName()!=null)
				webankParam.setwMerchantName(configDto.getWwMerchantName());
				if(configDto.getWwMerchantAbbreviation()!=null)
				webankParam.setwMerchantAbbreviation(configDto.getWwMerchantAbbreviation());
				if(configDto.getQrMerchantId()!=null)
				webankParam.setQrMerchantId(configDto.getQrMerchantId());
				if(configDto.getQrMerchantName()!=null)
				webankParam.setQrMerchantName(configDto.getQrMerchantName());
				if(configDto.getQrMerchantAbbreviation()!=null)
				webankParam.setQrMerchantAbbreviation(configDto.getQrMerchantAbbreviation());
				if(configDto.getQrAliMerchantId()!=null)
				webankParam.setQrAliMerchantId(configDto.getQrAliMerchantId());
				webankParam.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());

				if(checkWebankPrjIdExit(configDto.getPrjId())){ //存在
				    webankParamWriteMapper.updateByPrjIdKeySelective(webankParam);
				}else{											//不存在
				    webankParamWriteMapper.insertSelective(webankParam);
				}
			}catch(Exception e){
			    logger.error("saveOrUpdateParam error.", e);
				errorMSG.append("插入微众参数异常："+e.getMessage());
			}

		}
		//电子章
		ConfigurationQiyuesuo qiyuesuo = new ConfigurationQiyuesuo();
		qiyuesuo.setProjectId(configDto.getPrjId());
		if(configDto.getQiyuesuoAccessToken()!=null)
		qiyuesuo.setAccessToken(configDto.getQiyuesuoAccessToken());
		if(configDto.getQiyuesuoAccessSecret()!=null)
		qiyuesuo.setAccessSecret(configDto.getQiyuesuoAccessSecret());
		if(configDto.getQiyuesuoSealId()!=null)
		qiyuesuo.setSealId(Long.valueOf(configDto.getQiyuesuoSealId()));
		try {
			configurationQiyuesuoService.save(qiyuesuo);
		} catch (Exception e1) {
			e1.printStackTrace();
			errorMSG.append("插入电子章参数异常："+e1.getMessage());
		}
		//云丁门锁
		try {
		    List<DdingProjectConfig> ddingConfigList = configDto.getDdingProjectConfigList();
			if(!CollectionUtils.isEmpty(ddingConfigList)){
				ddLockService.saveDdingProjectConfig(ddingConfigList.toArray(new DdingProjectConfig[ddingConfigList.size()]));
			}
		} catch (Exception e1) {
			errorMSG.append("插入云丁参数异常："+e1.getMessage());
   
		}

        try
        {
            // 保存银石支付配置
            shiJiPaymentService.saveShiJiProjectConfig(configDto.getShiJiProjectConfig());
        }
        catch (LandseaException e)
        {
            errorMSG.append("保存银石项目配置失败：" + e.getErrorDesc());
        }
		JsonMapper jsonmapper = new JsonMapper();
		String result = "";
		if(errorMSG.length()==0){
			map.put("status", 0);
			try {
				result = jsonmapper.toJson(map);
			} catch (IOException e) {
			    logger.error("achieveDayFreezeEnergy error.", e);
				result = "{\"status\":0}";
			}
		}else{
			map.put("status", -1);
			map.put("errMsg", errorMSG);
			try {
				result = jsonmapper.toJson(map);
			} catch (IOException e) {
			    logger.error("saveOrUpdateParam error.", e);
				result = "{\"status\":-1, \"errMsg\":\""+errorMSG+"\"}";
			}
		}
		return result;
	}

	private boolean checkWebankPrjIdExit(Integer prjId) {
		WebankParam webankParam = webankParamReadMapper.selectByPrjId(prjId);

		if(webankParam!=null){
			return true;
		}else{
			return false;
		}
	}

	private boolean validateParams(ParamConfigDTO configDto) {
		return true;
	}

	@Override
	public HashMap<String, Object> getParamByPrjId(Integer id) {
		StringBuffer errorMSG = new StringBuffer();
		ParamConfigDTO paramConfigDTO = new ParamConfigDTO();

		//项目信息
		ProjectDetailDTO project = projectService.getProjectDetail(id);
		if(project!=null){
			if(project.getPrjCode()!=null)
			paramConfigDTO.setPrjCode(project.getPrjCode());
			if(project.getPrjName()!=null)
			paramConfigDTO.setPrjName(project.getPrjName());
			if(project.getArea()!=null)
			paramConfigDTO.setCity(project.getArea());
		}
		//微众收银台参数
		WebankParam webankParam = webankParamReadMapper.selectByPrjId(id);
		paramConfigDTO.setPrjId(id);
		if(webankParam!=null){
			if(webankParam.getQrMerchantId()!=null)
			paramConfigDTO.setQrMerchantId(webankParam.getQrMerchantId());
			if(webankParam.getQrMerchantName()!=null)
			paramConfigDTO.setQrMerchantName(webankParam.getQrMerchantName());
			if(webankParam.getQrMerchantAbbreviation()!=null)
			paramConfigDTO.setQrMerchantAbbreviation(webankParam.getQrMerchantAbbreviation());
			if(webankParam.getQrAliMerchantId()!=null)
			paramConfigDTO.setQrAliMerchantId(webankParam.getQrAliMerchantId());
			if(webankParam.getwMerchantId()!=null)
			paramConfigDTO.setWwMerchantId(webankParam.getwMerchantId());
			if(webankParam.getwMerchantName()!=null)
			paramConfigDTO.setWwMerchantName(webankParam.getwMerchantName());
			if(webankParam.getwMerchantAbbreviation()!=null)
			paramConfigDTO.setWwMerchantAbbreviation(webankParam.getwMerchantAbbreviation());
		}

		//保存电子章
		try {
			ConfigurationQiyuesuo configurationQiyuesuo = (ConfigurationQiyuesuo) configurationQiyuesuoService.get(id);
			if(configurationQiyuesuo!=null){
				if(configurationQiyuesuo.getAccessToken()!=null)
					paramConfigDTO.setQiyuesuoAccessToken(configurationQiyuesuo.getAccessToken());
					if(configurationQiyuesuo.getAccessSecret()!=null)
					paramConfigDTO.setQiyuesuoAccessSecret(configurationQiyuesuo.getAccessSecret());
					if(configurationQiyuesuo.getSealId()!=null)
					paramConfigDTO.setQiyuesuoSealId(String.valueOf(configurationQiyuesuo.getSealId()));
			}
		} catch (Exception e) {
		    logger.error("getParamByPrjId error.", e);
			errorMSG.append("获取电子章参数异常："+e.getMessage());
		}

		//保存云丁门锁
		try {
			List<DdingProjectConfig> result = ddLockService.getDdingProjectConfig(id);
			if(result!=null){
				paramConfigDTO.setDdingProjectConfigList(result);
			}
		} catch (Exception e) {
		    logger.error("getParamByPrjId error.", e);
			errorMSG.append("获取云丁参数异常："+e.getMessage());
		}

		HashMap<String,Object> map = new HashMap<String,Object>();
		if(errorMSG.length()==0){
			map.put("status", 0);
			map.put("data", paramConfigDTO);
		}else{
			map.put("status", -1);
			map.put("errorMSG", errorMSG);
			map.put("data", paramConfigDTO);
		}
		return map;
	}
}
